package com.example.bbs.util;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.MimeTypeMap;

import com.example.bbs.base.Data;
import com.example.bbs.bean.MediaData;
import com.example.bbs.config.HttpConstant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
import java.util.function.BiConsumer;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class FileUtil {

    public static final String UPLOADED_URL_PREFIX = "http";
    public static final String BASE_PREFERENCES_FILE = "base";
    static final String LOG_TAG = FileUtil.class.getSimpleName();

    private FileUtil() throws InstantiationException {
        throw new InstantiationException("This class is not for instantiation");
    }

    /**
     * Get a file path from a Uri. This will get the the path for Storage Access
     * Framework Documents, as well as the _data field for the MediaStore and
     * other file-based ContentProviders.
     *
     * @param uri The Uri to query.
     */
    // https://blog.csdn.net/jenly121/article/details/48373861
    public static String getFilePath(final Uri uri) {

        @SuppressLint("ObsoleteSdkInt")
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(Data.context, uri)) {
            // ExternalStorageProvider
            if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            // TODO(Low): error here, check it later
            /*else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.parseLong(id));

                return getDataColumn(context, contentUri, null, null);
            }*/
            // MediaProvider
            else if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                final String[] selectionArgs = new String[] { split[1] };

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                return getUriColumn(contentUri, "_data", "_id=?", selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getUriColumn(uri, "_data", null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static String getUriColumn(Uri uri, String column, String selection, String[] selectionArgs) {
        try (Cursor cursor = Data.context.getContentResolver().query(
                uri, new String[] { column }, selection, selectionArgs, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
        return null;
    }

    public static File copyContentUriToFile(Uri uri) {
        if (uri == null || !uri.getScheme().equals(ContentResolver.SCHEME_CONTENT))
            return null;
        String displayName = UUID.randomUUID().toString() + "." + getExtension(uri);

        try {
            File file = new File(Data.context.getCacheDir().getAbsolutePath(), displayName);
            if (!file.createNewFile())
                return null;
            copyToFile(Data.context.getContentResolver().openInputStream(uri), file);
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getExtension(Uri uri) {
        return MimeTypeMap.getSingleton().getExtensionFromMimeType(Data.context.getContentResolver().getType(uri));
    }

    public static Uri downloadFile(String urlStr) {
        try {
            HttpURLConnection urlConn = (HttpURLConnection) new URL(urlStr).openConnection();
            File file = new File(Data.context.getCacheDir().getAbsolutePath(), MediaData.fetchNameOnline(urlStr));
            boolean downloaded = false;
            if (!file.exists()) {
                if (!file.createNewFile()) {
                    Log.w(LOG_TAG, "create file failed when downloading");
                }
                copyToFile(urlConn.getInputStream(), file);
                downloaded = true;
            }
            Uri uri = Uri.fromFile(file);
            Log.i(LOG_TAG, (downloaded ? "downloading" : "finding file" ) + "success: uri: " + uri.toString());
            return uri;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static void copyToFile(InputStream inputStream, File file) {
        try {
            FileOutputStream outputStream = new FileOutputStream(file);
            byte [] buffer = new byte[4 * 1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void uploadMediaData(String localUrl, int type, BiConsumer<Boolean, String> callback) {
        if (localUrl == null || localUrl.isEmpty()) {
            Log.w(LOG_TAG, "empty url, skip");
            return;
        }
        String filePath = FileUtil.getFilePath(Uri.parse(localUrl));
        File mediaFile;
        String name = UUID.randomUUID().toString();
        if (filePath == null || filePath.isEmpty()) {
            Log.d(LOG_TAG, "cannot find file from uri");
            mediaFile = copyContentUriToFile(Uri.parse(localUrl)); // 找不到路径就新建一个
            name += '.' + getExtension(Uri.parse(localUrl));
        } else {
            mediaFile = new File(filePath);
            name += filePath.substring(filePath.lastIndexOf('.'));
        }
        MediaType mediaType = MediaType.Companion.parse(
                MediaData.fetchTypeName(type) + "; charset=utf-8");
        RequestBody fileBody = RequestBody.Companion.create(mediaFile, mediaType);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(HttpConstant.FIELD_PARAM_1, "" + type)
                .addFormDataPart(HttpConstant.FIELD_PARAM_DATA, name, fileBody)
                .build();
        String finalName = name;
        HttpUtil.postAsync(HttpConstant.REQUEST_UPLOAD, requestBody, (response) -> {
            boolean uploaded = response != null && response.getBoolean(HttpConstant.FIELD_REPLY);
            Log.i(LOG_TAG, "add media " + (uploaded ? "success" : "failure") +
                    ": type: " + type + ", name: " + finalName + ", filepath: " + filePath);
            callback.accept(uploaded, MediaData.fetchBaseUrl(type) + finalName);
        });
    }
}
